package handlers

import (
	"github.com/gin-gonic/gin"
	"happy-sys/models"
	"happy-sys/pkg"
	"strconv"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段数据不能为空",
		})
		return
	}
	if password != pkg.Md5Str(password) {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码不能重复码",
		})
		return
	}
	data := models.User{
		Username: username,
		Password: password,
	}
	err := models.DB.Find(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}
func Add(c *gin.Context) {
	name := c.PostForm("name")
	video := c.PostForm("video")
	if name == "" || video == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.Book{
		Name:  name,
		Video: video,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var book []models.Book
	models.DB.Order("DESC").Limit(size).Offset(offset).Find(&book)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表成功",
		"book": book,
	})
	return
}
